package com.javasm.mingming.login.jwt;

import com.javasm.mingming.common.utils.TokenUtil;
import com.javasm.mingming.login.entity.LoginUserDetails;
import com.javasm.mingming.login.service.impl.UidUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author javasm
 * @version 0.1
 * @className JwtProvider
 * @descriptioin:
 * @date 2025/1/13 16:01
 * @since jdk11
 */
@Component
public class JwtProvider implements AuthenticationProvider {

    @Resource
    UidUserDetailsService userDetailsService;
    @Resource
    HttpServletResponse response;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authentication;
        String tokenStr = jwtToken.getToken();
        String uidStr = TokenUtil.parse(tokenStr);
        //根据uid查询用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(uidStr);
        if (userDetails == null){
            throw new BadCredentialsException("用户不存在");
        }
        //生成新的token
        String newTokenStr = TokenUtil.generateToken(uidStr);
        response.setHeader(TokenUtil.Server_Token_Key,newTokenStr);
        response.setHeader("Access-Control-Expose-Headers",TokenUtil.Server_Token_Key);
        //生成新的对象
        JwtToken newJwtToken = new JwtToken(userDetails);
        return newJwtToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return JwtToken.class.isAssignableFrom(aClass);
    }
}
